#!/bin/sh

PORTSDIR=${PORTSDIR:=/usr/ports}

problems=0

ensure_sysctl_eq()
{
	sysctl="$1" requirement="$2" severity="$3"
	value=`sysctl -n "${sysctl}"`
	if [ ! ${value} -eq ${requirement} ]; then
		echo "${severity}: `sysctl -d ${sysctl}` is ${value} and should be ${requirement}."
		problems=$((problems+1))
	fi
}
ensure_sysctl_ge()
{
	sysctl="$1" threshold="$2" severity="$3"
	value=`sysctl -n "${sysctl}"`
	if [ ! ${value} -ge ${threshold} ]; then
		echo "${severity}: `sysctl -d ${sysctl}` is ${value} and should be at least ${threshold}."
		problems=$((problems+1))
	fi
}

# Entry point

case `uname -r` in
	6*)
		if [ ! -r /etc/libmap.conf ] || [ "`grep -Ec '^[^#]*libpthread.so(.[:digit:])?[:blank:]*.*libthr.so(.[:digit:])?' /etc/libmap.conf`" != 2 ]; then
			echo "E: Mono can't be build with FreeBSD 6.X kse(2) pthreads."
			echo "   KSE was disabled in FreeBSD 7.0 and removed in FreeBSD 8.0."
			echo "   You can workaround this error adding the following to /etc/libmap.conf:"
			echo "   libpthread.so.2  libthr.so.2"
			echo "   libpthread.so    libthr.so"
			problems=$((problems+1))
		fi

		;;
	7*) ;;
	8*) ;;
	*)
		echo "E: Only FreeBSD 6.x, 7.x and 8.x are supported."
		problems=$((problems+1))
		;;
esac

ensure_sysctl_ge kern.ipc.semmni 40 W
ensure_sysctl_ge kern.ipc.semmns 300 W

if [ `sysctl -n security.jail.jailed` -eq 1 ]; then
	ensure_sysctl_eq security.jail.sysvipc_allowed 1 E
	problems=$((problems+1))
fi

if mount -p | awk ' BEGIN { ok = 0 } $2 == "/proc" && $3 == "procfs" { ok = 1 } END { exit ok }'; then
	echo "W: devfs(5) is not mounted. Some features will be broken."
	problems=$((problems+1))
fi

CFLAGS="$(make -C "${PORTSDIR}/lang/mono" -V CFLAGS)"
case "${CFLAGS}" in
	"-O2 -fno-strict-aliasing -pipe") ;;	# Default (FreeBSD 7.2-STABLE)
	"-O2 -pipe -fno-strict-aliasing") ;;	# Default (FreeBSD 9.0-RC1)
	"-pipe -g") ;;				# WITH_DEBUG=
	*)
		echo "W: You are compiling mono with customized CFLAGS (${CFLAGS})."
		problems=$((problems+1))
		;;
esac

echo "${problems} problems(s) reported."
